from socket import *
from Tkinter import *
import sys
import pickle
import thread

class Personne:
    #nom
    #telephonne
    def __init__(self, nom="nom inconnu",telephone="pas de numero"):
        self.nom=nom
        self.telephone=telephone
        
    def toString(self):
        #print ("nom" , self.getNom() , "numero" , self.getTelephone())
        return "nom : " + self.getNom() + " - numero : " + self.getTelephone()
        
    def getNom(self):
        return self.nom
    
    def getTelephone(self):
        return self.telephone
    
    def lenTelephone(self):
        return len(self.telephone)
    
    
class Client:
    #serverHost
    #serverPort
    #soc
    def __init__(self, serverHost, serverPort):
        self.nom=''
        self.fenetre = None
        self.serverHost = serverHost
        self.serverPort = serverPort
        self.soc_emission = socket(AF_INET, SOCK_STREAM)
        self.soc_reception = socket(AF_INET, SOCK_STREAM)
        
    ###########################################################################
    def ouvrirConnexion(self):
        try:
            #creation de la socket reception
            #creation de la socket emission
            self.soc_emission.connect((self.serverHost, self.serverPort))
            #recuperation de du port de la socket reception
            #envoi du num port au serveur
        except Exception, inst:
            print inst
            #exit??????
            
    def fermerConnexion(self):
        try:
            self.soc_emission.close()
            self.soc_reception.close()
        except Exception, inst:
            print inst
    
    def sIdentifierAuPresDuServeur(self):
        print 'Yo!!' + self.nom
            
    def lancerLaDiscution(self):
        self.nom = self.savoirQuiJeSuis()
        print self.nom
        try:
            self.sIdentifierAuPresDuServeur()
        except Exception, inst:
            print inst
            sys.exit()
        root = Tk()
        root.title('Mini chat : '+self.nom)
        self.fenetre = MyFenetre(root, self) 
        self.fenetre.pack()
        #thread
        thread.start_new_thread(ecouterServeur)
        root.mainloop()
    
    def ecouterServeur(self):
        while 1:
            try:
                texte = self.soc_reception.recvfrom(1024)
            except Exception, ins:
                print inst
            else:
                self.fenetre.afficherMSG(texte)
            
    def envoyerMSG(self, texte):
        try:
            self.soc_emission.sendto(data, texte)
        except Exception, ins:
            print inst
        
    def mAjInfoServer(self):
        print 'mAjInfoServer'
        
    ###########################################################################
    def savoirQuiJeSuis(self):
        nom = ""
        contacts = []
        try:
            f=open("./save", "r")
        except Exception, inst:
            return inst
        else:
            contacts = pickle.load(f)
            f.close()
            print 'Aide memoire : liste des personnes'
            for personne in contacts :
                print "     - " + personne.getNom()
            nom = raw_input('Qui etes-vous?')[:-1]
            print "Bienvenue " + nom
        return nom
        
    def getPersonne(self):
        return self.personne
    
    def setPersonne(self, personne):
        self.personne = personne

    ###########################################################################



class MyFenetre(Frame):
    def __init__(self, client): 
        Frame.__init__(self)
        
        self.client = client
                
        self.text_entre = Text(self, width=50, height = 8)
        self.text_entre.config(wrap=WORD)
        self.boutton_profil = Button(self, text=" Mise a jour de mon profil ", relief='groove', command = self.profil())
        self.text_affiche = Text(self, width=50, height = 8, state= 'disabled')
        self.text_affiche.config(wrap=WORD)
        self.button_quit = Button(self, text=" Quitter ", relief='groove', command = self.quit)
        self.lab_auteur = Label(self, text=" Coded by Xavier MARY ", font= "arial 7")
        self.button_envoi = Button(self, text=" Envoyer le message ", fg='red', command = self.envoyerMSG)
        
        self.text_affiche.pack(pady = 5, padx = 5)
        self.boutton_profil.pack()
        self.text_entre.pack(pady = 5, padx = 5)    
        self.button_envoi.pack(side = RIGHT, pady = 5, padx = 5)
        self.button_quit.pack(side = LEFT, pady = 5, padx = 5)
        self.lab_auteur.pack(side = BOTTOM, pady = 5, padx = 5)
        
    def foo(self):
        print "foo()"
    
    def afficherMSG(self, texte):
        self.text_affiche.config(state='normal')
        self.text_affiche.insert(END, texte)
        self.text_affiche.config(state='disabled')
    
    def envoyerMSG(self):
        texte = self.text_entre.get(1.0, END)
        self.text_entre.delete(1.0, END)
        self.client.envoyerMSG(texte)
        
    def profil(self):
        print "profil()"
        
        
        
        
        
        
        
        
        
"""
def serveclient(c):
    global v,nclnt,vlock,nclntlock
    while 1:
        k = c.recv(1)
        if k == '': break
        vlock.acquire()
        v += k
        vlock.release()
        c.send(v)
    c.close()
    nclntlock.acquire()
    nclnt -= 1
    nclntlock.release()


lstn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = int(sys.argv[1])
lstn.bind(('', port))
lstn.listen(5)
v = ''
vlock = thread.allocate_lock()
nclnt = 2
nclntlock = thread.allocate_lock()
for i in range(nclnt):
    (clnt,ap) = lstn.accept()
    thread.start_new_thread(serveclient,(clnt,))
lstn.close()
while nclnt > 0: pass
print 'the final value of v is', v
"""
##########
## MAIN ##
##########

def commenceprogramme():
    #client
    clt = Client("localhost", 2020)
    clt.ouvrirConnexion()
    clt.sIdentifierAuPresDuServeur()
    clt.lancerLaDiscution()
    clt.fermerConnexion()
    
if __name__=="__main__" :
    commenceprogramme()
        